<?php
/*
 * @copyright        [YouNet_COPYRIGHT]
 * @author           YouNet Development
 * @package          Module_Contactimporter
 * @version          2.06
 *
 */
defined('PHPFOX') or exit('NO DICE!');
?>

<?php
class Contactimporter_Service_Process extends Phpfox_Service
{
    public function addQueue($provider = '', $total = 0, $message = '', $friends_ids = '')
	{
		$iUserId = Phpfox::getUserId();
        $session = '';
        if ($provider == 'facebook')
        {
            $oFacebook = Phpfox::getService('contactimporter')->initFB();
            $session = serialize($oFacebook->getSession());
        }
        if ($provider == 'twitter' && isset($_SESSION['twitter']))
        {
            $session = serialize($_SESSION['twitter']);
        }
        $this->database()->insert(Phpfox::getT('contactimporter_queue'), array('user_id' => $iUserId, 'session' => $session, 'provider' => $provider, 'total' => $total, 'message' => $message, 'friend_ids' => $friends_ids, 'time_stamp' => PHPFOX_TIME));
	}

    public function cronSendInvite($sProvider = '', $iUserId = 0)
	{      
        $iMaxDaily = Phpfox::getService('contactimporter.setting')->getMaxDaily();
        $sServerId = Phpfox::getLib('request')->getServer('PHPFOX_SERVER_ID');
        $iMaxSent = 5;        
        
        $aConds[] = 'AND status = "pending"';
        $aConds[] = 'AND (server_id IS NULL OR server_id = "' . $sServerId . '")';
        if ($sProvider)
        {
            $aConds[] = 'AND provider = "' . $sProvider . '"';
        }
        if ($iUserId)
        {
            $aConds[] = 'AND user_id = "' . $iUserId . '"';
        }        
        $aRow = $this->database()->select('*')
            ->from(Phpfox::getT('contactimporter_queue'))
            ->where($aConds)
            ->limit(1)
            ->order('queue_id ASC')
            ->execute('getRow');
        
        print_r($aRow);
        print_r('<hr/>');
        
        if (!$aRow) return false;
        
        if ($aRow['status'] == 'success')
        {
            return false;    
        }
        
        if ($aRow['server_id'] == null || $aRow['server_id'] == '')
        {
            $aRow['server_id'] = $sServerId;
            $this->database()->update(Phpfox::getT('contactimporter_queue'), array('server_id' => $sServerId), "queue_id = " . $aRow['queue_id']);
        }      
        
        $iQueueId = $aRow['queue_id'];
        $iUserId = $aRow['user_id'];
        $iTotal = $aRow['total'];
        $iSuccess = $aRow['success'];
        $iFails = $aRow['fail'];
        $sProvider = $aRow['provider'];
        $sMessage = $aRow['message'];
        $sFriendIds = isset($aRow['friend_ids']) ? $aRow['friend_ids'] : '';
        $sFailIds = isset($aRow['fail_ids']) ? $aRow['fail_ids'] : '';
        $sNext = isset($aRow['next']) ? $aRow['next'] : '';
        
        if ($sProvider == 'yahoo' || $sProvider == 'gmail' || $sProvider == 'hotmail')
        {
            if ($aRow['friend_ids'] == null  || $aRow['friend_ids'] == '')
            {
                $this->database()->delete(Phpfox::getT('contactimporter_queue'), "queue_id = " . $aRow['queue_id']);
            }
        }
        
        $iYear = date('Y', PHPFOX_TIME);
        $iMonth = date('m', PHPFOX_TIME);
        $iDay = date('d', PHPFOX_TIME);        
        $iStartTimeOnDate = mktime(0, 0, 0, $iMonth, $iDay, $iYear);
        $iEndTimeOnDate = mktime(23, 59, 59, $iMonth, $iDay, $iYear);
        
        $aConds = array();        
        $aConds[] = "AND time_stamp >= $iStartTimeOnDate AND time_stamp <= $iEndTimeOnDate";
        $aDaily = $this->database()->select('*')
            ->from(Phpfox::getT('contactimporter_queue_daily'))
            ->where($aConds)            
            ->limit(1)            
            ->execute('getRow');
        if (!$aDaily)
        {
            $aDaily = array('queue_id' => $iQueueId, 'total' => 0, 'time_stamp' => PHPFOX_TIME);
            $aDaily['daily_queue_id'] = $iDailyQueueId = $this->database()->insert(Phpfox::getT('contactimporter_queue_daily'), $aDaily);
        }        
        
        print_r($aDaily);
        print_r('<hr/>');
        
        print_r ($iMaxDaily);
        print_r('<hr/>');
        
        if ($iMaxDaily > 0)
        {        
            if ($iMaxDaily - $aDaily['total'] <= 0)
            {
                return false;    
            }
            if ($iMaxDaily - $aDaily['total'] < $iMaxSent)
            {
                $iMaxSent = $iMaxDaily - $aDaily['total'];
            }
        }
       
        print_r ($iMaxSent);
        print_r('<hr/>');
        
        if ($iSuccess + $iFails >= $iTotal)
        {            
            if ($iFails == 0)
            {
                $aUpdate['fail_ids'] = '';
            }
            $aUpdate['status'] = 'success';
            $this->database()->update(Phpfox::getT('contactimporter_queue'), $aUpdate, "queue_id = " . $iQueueId);
            return;
        }
                    
        $aUser = Phpfox::getService('user')->get($iUserId, true);
		$sEmail = $aUser['email'];
        $aInvite = $this->database()->select('invite_id')
            ->from(Phpfox::getT('invite'))
            ->where('email = \'' . $sEmail . '\'')
            ->execute('getSlaveRow');
        if ($aInvite)
        {
            $iInvite = $aInvite['invite_id'];
        }
        else
        {
            $iInvite = Phpfox::getService('invite.process')->addInvite($sEmail, $iUserId);
        }
        $sLink = Phpfox::getLib('url')->makeUrl('invite', array('id' => $iInvite));

        $aFailIds = $sFailIds ? unserialize($sFailIds) : array();
        $aResult = array();
        if ($sProvider == 'facebook')
        {
            $aSetting = Phpfox::getService('contactimporter.setting')->getApiSetting($sProvider);
            $aSetting['api_params'] = unserialize($aSetting['api_params']);
            $oFacebook = Phpfox::getService('contactimporter')->initFB();
            $aSession = unserialize($aRow['session']);
            $oFacebook->setSession($aSession);
            print_r($oFacebook);
            print_r('<hr/>');
                
            $aFriendIds = $aSendIds = array();            
            if (!$sFriendIds || !unserialize($sFriendIds))
            {
                Phpfox_Error::skip(false);
                print_r('START GET FRIENDS <hr/>');
                try
                {
                    $aFriends = $oFacebook->api(array(
                        'method' => 'fql.query',
                        'query' => "SELECT uid2 FROM friend WHERE uid1 = me()"
                    ));
                } 
                catch (Exception $e)
                {
                    var_dump($e);
                }
                print_r('END GET FRIENDS <hr/>');
                
                print_r($aFriends);
                print_r('<hr/>');
                
                $aFriendIds = array();
                if ($aFriends)
                {
                    foreach ($aFriends as $aFriend)
                    {
                        $aFriendIds[] = $aFriend['uid2'];
                    }
                }
                $sFriendIds = serialize($aFriendIds);
                $this->database()->update(Phpfox::getT('contactimporter_queue'), array('friend_ids' => $sFriendIds), "queue_id = " . $iQueueId);
            }
            if ($sFriendIds)
            {
                $aFriendIds = unserialize($sFriendIds);
            }
            $aNewFriendIds = array();
            if ($aFriendIds)
            {
                $i = 0;
                foreach ($aFriendIds as $iFriendId)
                {
                    if ($i < $iMaxSent)
                    {
                        $aSendIds[] = $iFriendId;
                    }
                    else
                    {
                        $aNewFriendIds[] = $iFriendId;
                    }
                    $i++;
                }
            }
            $aFriendIds = $aNewFriendIds;
            if ($aSendIds)
            {
                $iSents = $iFails = 0;
                foreach ($aSendIds as $iId)
                {
                    try
					{
                        $aResult[] = 'Start send message to ' . $iId;
                        $me = $oFacebook->api('/me');
                        $sInviterName = $me['name'];                        
                        $sName = '';
                        $sMessage = Phpfox::getPhrase('contactimporter.invitation_message_for_social', array('message' => $sMessage, 'full_name' => $sInviterName, 'host' => phpfox::getParam('core.path'), 'link' => $sLink));				
                        $aParam = array (
                            'message' => $sMessage,					
                            'name' => $sName,
                            'caption' => Phpfox::getParam('core.path'),
                            'description' => Phpfox::getParam('core.global_site_title')
                        );                        
                        $oFacebook->api('/'. $iId . '/feed', 'POST', $aParam);
                        $aResult[] = 'End send message to ' . $iId;
                        $iSents++;
                    }
                    catch (Exception $e)
                    {   print_r($e);
                        if (!in_array($iId, $aFailIds))
                        {
                            $aFailIds[] = $iId;
                            $aFriendIds[] = $iId;
                        }
                        else
                        {
                            $iFails++;
                        }
                    }
                }
                $aResult[] = 'Sent: ' . $iSents;
                if ($iSents > 0 || $iFails > 0)
                {
                    $sFailIds = $aFailIds ? serialize($aFailIds) : '';
                    $sFriendIds = $aFriendIds ? serialize($aFriendIds) : '';
                    $iSuccess = $iSuccess + $iSents;                    
                    if ($sFriendIds == '')
                    {
                        $iFails = $iTotal - $iSuccess;
                    }
                    if ($iSuccess + $iFails >= $iTotal)
                    {
                        $aUpdate['status'] = 'success';
                    }
                    else
                    {
                        $aUpdate['server_id'] = null;
                    }
                    if ($iSuccess > $iTotal)
                    {
                        $iSuccess = $iTotal;
                        $iFails = 0;
                        $sFriendIds = '';
                        $sFailIds = '';
                    }
                    $aUpdate = array (
                        'success' => $iSuccess,
                        'fail' => $iFails,
                        'friend_ids' => $sFriendIds,
                        'fail_ids' => $sFailIds
                    );
                    $aResult[] = 'Update queue';
                    $this->database()->update(Phpfox::getT('contactimporter_queue'), $aUpdate, "queue_id = " . $iQueueId);
                    if (isset($aDaily['daily_queue_id']) && $aDaily['daily_queue_id'])
                    {
                        $this->database()->update(Phpfox::getT('contactimporter_queue_daily'), array('total' => $aDaily['total'] + $iSents), "daily_queue_id = " . $aDaily['daily_queue_id']);
                    }
                    $aResult[] = 'Update statistic';
                    Phpfox::getService('contactimporter.process')->updateStatistic($iUserId, 0, $iSents, $sProvider);
                    $aResult[] = 'Remain: ' . count($aFriendIds);
                }
            }
        }

        if ($sProvider == 'twitter')
        {
            $aSetting = Phpfox::getService('contactimporter.setting')->getApiSetting($sProvider);
            $aSetting['api_params'] = unserialize($aSetting['api_params']);
            require_once(PHPFOX_DIR.'module'.PHPFOX_DS.'contactimporter'.PHPFOX_DS.'include'.PHPFOX_DS.'component'.PHPFOX_DS.'controller'.PHPFOX_DS.'Apiconnection'.PHPFOX_DS.'twitter.php');
            $aSession = unserialize($aRow['session']);
            if (!$aSession)
            {
                return false;
            }
            $oTwitter = new Twitter($aSetting['api_params']['appid'], $aSetting['api_params']['secret']);
            $oTwitter->setOAuthToken($aSession['oauth_token']);
            $oTwitter->setOAuthTokenSecret($aSession['oauth_token_secret']);
            $aFriendIds = $aSendIds = array();
            if (!$sFriendIds)
            {
                list($sNext, $aFriendIds) = $oTwitter->followersIds(null, $aSession['user_id']);
                $sFriendIds = serialize($aFriendIds);
                $this->database()->update(Phpfox::getT('contactimporter_queue'), array('friend_ids' => $sFriendIds, 'next' => $sNext), "queue_id = " . $iQueueId);
            }
            if ($sFriendIds)
            {
                $aFriendIds = unserialize($sFriendIds);
            }
            $aNewFriendIds = array();
            if ($aFriendIds)
            {
                $i = 0;
                foreach ($aFriendIds as $iFriendId)
                {
                    if ($i < $iMaxSent)
                    {
                        $aSendIds[] = $iFriendId;
                    }
                    else
                    {
                        $aNewFriendIds[] = $iFriendId;
                    }
                    $i++;
                }
            }
            $aFriendIds = $aNewFriendIds;

            if ($aSendIds)
            {
                $iSents = $iFails = 0;
                $sMessage2 = $sMessage;
                foreach ($aSendIds as $iId)
                {
                    try
					{
                        $sMessage = substr($sMessage2, 0, 120 - strlen($sLink)). ' ' . $sLink;
                        $aResult[] = 'Start send message to ' . $iId;
                        $oTwitter->directMessagesNew($sMessage, null, $iId);
                        $aResult[] = 'End send message to ' . $iId;
                        $iSents++;
                    }
                    catch (Exception $e)
                    {
                        if (!in_array($iId, $aFailIds))
                        {
                            $aFailIds[] = $iId;
                            $aFriendIds[] = $iId;
                        }
                        else
                        {
                            $iFails++;
                        }
                    }
                }
                $aResult[] = 'Sent: ' . $iSents;
                if ($iSents > 0 || $iFails > 0)
                {
                    $sFailIds = $aFailIds ? serialize($aFailIds) : '';
                    $sFriendIds = $aFriendIds ? serialize($aFriendIds) : '';
                    $iSuccess = $iSuccess + $iSents;
                    if ($sFriendIds == '' && $sNext == '')
                    {
                        $iFails = $iTotal - $iSuccess;
                    }
                    if ($iSuccess + $iFails >= $iTotal)
                    {
                        $aUpdate['status'] = 'success';
                    }
                    else
                    {
                        $aUpdate['server_id'] = null;
                    }
                    if ($iSuccess > $iTotal)
                    {
                        $iSuccess = $iTotal;
                        $iFails = 0;
                        $sFriendIds = '';
                        $sFailIds = '';
                    }
                    $aUpdate = array (
                        'success' => $iSuccess,
                        'fail' => $iFails,
                        'friend_ids' => $sFriendIds,
                        'fail_ids' => $sFailIds
                    );
                    $aResult[] = 'Update queue';
                    $this->database()->update(Phpfox::getT('contactimporter_queue'), $aUpdate, "queue_id = " . $iQueueId);
                    if (isset($aDaily['daily_queue_id']) && $aDaily['daily_queue_id'])
                    {
                        $this->database()->update(Phpfox::getT('contactimporter_queue_daily'), array('total' => $aDaily['total'] + $iSents), "daily_queue_id = " . $aDaily['daily_queue_id']);
                    }
                    $aResult[] = 'Update statistic';
                    Phpfox::getService('contactimporter.process')->updateStatistic($iUserId, 0, $iSents, $sProvider);
                    $aResult[] = 'Remain: ' . count($aFriendIds);
                    if (count($aFriendIds) == 0 && $iSuccess < $iTotal && $sNext)
                    {
                        list($sNext, $aFriendIds) = $oTwitter->followersIds(null, $aSession['user_id'], null, $sNext);
                        $sFriendIds = serialize($aFriendIds);
                        $this->database()->update(Phpfox::getT('contactimporter_queue'), array('friend_ids' => $sFriendIds, 'next' => $sNext), "queue_id = " . $iQueueId);
                    }
                }
            }
        }

        if ($sProvider == 'yahoo' || $sProvider == 'gmail' || $sProvider == 'hotmail')
        {
            $aUser = $this->database()->select('*')
                ->from(Phpfox::getT('user'))
                ->where('user_id = '.$iUserId)
                ->execute('getRow');
            
            print_r ($aUser);
            print_r('<hr/>');
        
            if (!$aUser || !$sFriendIds) return false;

            $sSubject = array('invite.full_name_invites_you_to_site_title', array('full_name' => $aUser['full_name'], 'site_title' => Phpfox::getParam('core.site_title')));
            $oMail = Phpfox::getLib('mail');
            $aEmails = unserialize($sFriendIds);

            $aNewEmails = array();
            if ($aEmails)
            {
                $i = 0;
                foreach ($aEmails as $aEmail)
                {
                    if (is_object($aEmail))
                    {  
                       $sEmail = $aEmail->email;  
                    }
                    elseif (is_array($aEmail))
                    {
                        $sEmail = $aEmail['email'];  
                    }
                    else
                    {
                        $sEmail = $aEmail;  
                    }
                    
                    if ($i < $iMaxSent)
                    {
                        $aSendEmails[] = $sEmail;
                    }
                    else
                    {
                        $aNewEmails[] = $sEmail;
                    }                    
                    $i++;
                }
            }            
            $aEmails = $aNewEmails;
            foreach ($aSendEmails as $sEmail)
            {
                try
                {
                    $aInvite = $this->database()->select('invite_id')
                        ->from(Phpfox::getT('invite'))
                        ->where('email = "' . $sEmail . '" AND user_id = "' . $iUserId . '"')
                        ->execute('getSlaveRow');
                    if ($aInvite)
                    {
                        $iInviteId = $aInvite['invite_id'];
                    }
                    else
                    {
                        $iInviteId = Phpfox::getService('invite.process')->addInvite($sEmail, $iUserId);
                    }
                    $sLink = Phpfox::getLib('url')->makeUrl('invite', array('id' => $iInviteId));
                    $sBody = array('invite.full_name_invites_you_to_site_title_link', array('full_name' => $aUser['full_name'], 'site_title' => Phpfox::getParam('core.site_title') . '<br/>' . $sMessage, 'link' => $sLink));
                    $oMail->to($sEmail)
                        ->subject($sSubject)
                        ->message($sBody)
                        ->send();
                }
                catch (Exception $e)
                {
                }
            }
            $iFails = 0;
            $iSents = count($aSendEmails);
            $sFriendIds = $aEmails ? serialize($aEmails) : '';
            $iSuccess = $iSuccess + $iSents;
            if ($iSuccess > $iTotal)
            {
                $iSuccess = $iTotal;
                $iFails = 0;
                $sFriendIds = '';
                $sFailIds = '';
            }
            $aUpdate = array (
                'success' => $iSuccess,
                'fail' => $iFails ,
                'friend_ids' => $sFriendIds,
                'fail_ids' => ''
            );
            if ($iSuccess + $iFails >= $iTotal)
            {
                $aUpdate['status'] = 'success';
            }
            else
            {
                $aUpdate['server_id'] = null;
            }
            $aResult[] = 'Update queue';
            $this->database()->update(Phpfox::getT('contactimporter_queue'), $aUpdate, "queue_id = " . $iQueueId);
            if (isset($aDaily['daily_queue_id']) && $aDaily['daily_queue_id'])
            {
                $this->database()->update(Phpfox::getT('contactimporter_queue_daily'), array('total' => $aDaily['total'] + $iSents), "daily_queue_id = " . $aDaily['daily_queue_id']);
            }
            $aResult[] = 'Update statistic';
            Phpfox::getService('contactimporter.process')->updateStatistic($iUserId, $iSents, 0, $sProvider);
            $aResult[] = 'Remain: ' . count($aEmails);
        }
        print_r(implode('<br/>', $aResult));
    }

    public function cronSendMail()
	{
        $iTimeAgo = 2*60*60;
        Phpfox_Error::skip(true);
        $aConds[] = 'AND (q.total > 0)';
        $aConds[] = 'AND (q.success > 0)';        
        $aRows = $this->database()->select('q.*, u.email')
            ->from(Phpfox::getT('contactimporter_queue'), q)
            ->join(Phpfox::getT('user'), 'u', 'u.user_id = q.user_id')
            ->where($aConds)
            ->limit(100)
            ->execute('getRows');
        if (!$aRows) return false; 
        $oMail = Phpfox::getLib('mail');        
        $aResult = array();
        foreach ($aRows as $aRow)
        {           
            $sSubject = Phpfox::getPhrase('contactimporter.mail_subject_of_invitations', array('provider' => $aRow['provider'], 'site_title' => Phpfox::getParam('core.site_title')));
            if (($aRow['time_stamp_sendmail'] == null) || 
                ($aRow['time_stamp_sendmail'] != null && PHPFOX_TIME - $aRow['time_stamp_sendmail'] >= $iTimeAgo) ||
                ($aRow['total'] <= $aRow['success'] + $aRow['fail']) ||
                ($aRow['status'] == 'success'))
            {
                $aResult[] = 'Start send to ' . $aRow['email'];
                if (($aRow['total'] <= $aRow['success'] + $aRow['fail']) || ($aRow['status'] == 'success'))
                {
                    $sBody = Phpfox::getPhrase('contactimporter.your_invitations_successfully_sent', array('success' => $aRow['success'], 'fail' => $aRow['fail'], 'total' => $aRow['total']));
                }
                else
                {
                    $sBody = Phpfox::getPhrase('contactimporter.mail_body_of_invitations', array('success' => $aRow['success'], 'total' => $aRow['total']));
                }
                $oMail->to($aRow['email']);                
                $oMail->subject($sSubject);
                $oMail->message($sBody);
                $aResult[] = 'Return:' . print_r($oMail->send(), true);
                $aResult[] = 'End send to ' . $aRow['email'];
            }            
            if (($aRow['status'] == 'success') || 
                ($aRow['total'] <= $aRow['success'] + $aRow['fail']))
            {
                $this->database()->delete(Phpfox::getT('contactimporter_queue'), "queue_id = " . $aRow['queue_id']);
            }
            else
            {
                $this->database()->update(Phpfox::getT('contactimporter_queue'), array('time_stamp_sendmail' => PHPFOX_TIME), "queue_id = " . $aRow['queue_id']);
            }
        }
        print_r(implode('<br/>', $aResult));
    }

    public function sendInvite($sProvider, $aEmails, $sMessage, &$sError)
	{
        Phpfox_Error::skip(true);
        $iEmails = $iSocials = 0;
        if ($sProvider == 'facebook' || $sProvider == 'twitter' || $sProvider == 'linkedin')
        {
            $aIds = $aEmails;
            $sEmail = Phpfox::getUserBy('email');
            $aInvite = $this->database()->select('invite_id')
                ->from(Phpfox::getT('invite'))
                ->where('email = "' . $sEmail . '" AND user_id = "' . Phpfox::getUserId() . '"')
                ->execute('getSlaveRow');
            if ($aInvite)
            {
                $iInviteId = $aInvite['invite_id'];
            }
            else
            {
                $iInviteId = Phpfox::getService('invite.process')->addInvite($sEmail, Phpfox::getUserId());
            }
            $sLink = Phpfox::getLib('url')->makeUrl('invite', array('id' => $iInviteId));
            if ($sProvider == 'facebook')
            {
                foreach ($aIds as $sId)
                {
                    $oFacebook = Phpfox::getService('contactimporter.facebook');
                    if ($oFacebook->sendInvitation($sId, $sMessage, $sLink))
                    {
                        $iSocials++;
                    }
                }
            }
            if ($sProvider == 'twitter')
            {
                foreach ($aIds as $sId)
                {
                    $oTwitter = Phpfox::getService('contactimporter.twitter');
                    if ($oTwitter->sendInvitation($sId, $sMessage, $sLink, $sError))
                    {
                        $iSocials++;
                    }
                }
            }
            if ($sProvider == 'linkedin')
            {
                foreach ($aIds as $sId)
                {
                    $oLinkedIn = Phpfox::getService('contactimporter.linkedin');
                    if ($oLinkedIn->sendInvitation($sId, $sMessage, $sLink))
                    {
                        $iSocials++;
                    }
                }
            }            
        }

        if ($sProvider == 'yahoo' || $sProvider == 'gmail' || $sProvider == 'hotmail')
        {
            $sSubject = array('invite.full_name_invites_you_to_site_title', array('full_name' => Phpfox::getUserBy('full_name'), 'site_title' => Phpfox::getParam('core.site_title')));
            $oMail = Phpfox::getLib('mail');
            foreach ($aEmails as $sEmail)
            {
                $aInvite = $this->database()->select('invite_id')
                    ->from(Phpfox::getT('invite'))
                    ->where('email = "' . $sEmail . '" AND user_id = "' . Phpfox::getUserId() . '"')
                    ->execute('getSlaveRow');
                if ($aInvite)
                {
                    $iInviteId = $aInvite['invite_id'];
                }
                else
                {
                    $iInviteId = Phpfox::getService('invite.process')->addInvite($sEmail, Phpfox::getUserId());
                }
                $sLink = Phpfox::getLib('url')->makeUrl('invite', array('id' => $iInviteId));
                $sBody = array('invite.full_name_invites_you_to_site_title_link', array('full_name' => Phpfox::getUserBy('full_name'), 'site_title' => Phpfox::getParam('core.site_title') . '<br/>' . $sMessage, 'link' => $sLink));
                $oMail->to($sEmail)
                    ->subject($sSubject)
                    ->message($sBody)
                    ->send();
            }            
            $iEmails = count($aEmails);
        }
        $this->updateStatistic(Phpfox::getUserId(), $iEmails, $iSocials, $sProvider);
        return true;
    }

    public function updateStatistic($iUserId, $iEmails, $iSocials, $sProvider = '')
	{
		$aRow = $this->database()->select('*')
            ->from(Phpfox::getT('contactimporter_statistics'))
            ->where('user_id = ' . $iUserId)
            ->execute('getRow');
		if ($aRow != null)
		{
			$this->database()->update (Phpfox::getT('contactimporter_statistics'), array('emails' => $aRow['emails'] + $iEmails, 'socials' => $aRow['socials'] + $iSocials), 'statictis_id = '.$aRow['statictis_id']);
		}
		else
		{
			$this->database()->insert(Phpfox::getT('contactimporter_statistics'), array('user_id' => $iUserId, 'emails' => $iEmails, 'socials' => $iSocials));
		}
		
		$iTotal = $iEmails;
        if ($sProvider)
        {            
            if ($iSocials > 0)
            {
                $iTotal = $iSocials;
            }
			
			if ($iTotal > 0)
			{
				$aRow = $this->database()->select('*')
					->from(Phpfox::getT('contactimporter_contact'))
					->where('provider = "' . $sProvider . '" AND user_id = ' . $iUserId)
					->execute('getRow');
				if ($aRow != null)
				{
					$this->database()->update(Phpfox::getT('contactimporter_contact'), array('total' => $aRow['total'] + $iTotal), 'contact_id = ' . $aRow['contact_id']);
				}
				else
				{
					$this->database()->insert(Phpfox::getT('contactimporter_contact'), array('user_id' => $iUserId, 'provider' => $sProvider, 'total' => $iTotal));
				}
			}
		}
		
		if ($iTotal > 0)
		{
			$iYear = date('Y');
			$iMonth = date('n');
			$sConds  = ' user_id = ' . $iUserId;
			$sConds .= ' AND year = ' . $iYear;
			$sConds .= ' AND month = ' . $iMonth;
			$aRow = $this->database()->select('*')
				->from(Phpfox::getT('contactimporter_statistics_monthly'))
				->where($sConds)
				->execute('getRow');
			 
			if ($aRow != null)
			{
				$this->database()->update(Phpfox::getT('contactimporter_statistics_monthly'), array('total' => $aRow['total'] + $iTotal, 'time_stamp' => PHPFOX_TIME), $sConds);
			}
			else
			{
				$this->database()->insert(Phpfox::getT('contactimporter_statistics_monthly'), array('user_id' => $iUserId, 'year' => $iYear, 'month' => $iMonth, 'total' => $iTotal, 'time_stamp' => PHPFOX_TIME));
			}
		}
	}
    
    public function addSocial($iUserId, $sProvider = '', $sId, $sFullName, $sAvatar)
	{
        $aRow = $this->database()->select('*')
            ->from(Phpfox::getT('contactimporter_contact'))
            ->where("provider = '$sProvider' AND user_id = '$iUserId' AND friend_id = '$sId'")
            ->execute('getRow');
        $aInsert = array (
            'user_id' => $iUserId,
            'provider' => $sProvider,            
            'friend_id' => $sId,            
            'friend_name' => $sFullName,            
            'friend_avatar' => $sAvatar,            
            'time_stamp' => PHPFOX_TIME            
        );        
        $this->database()->insert(Phpfox::getT('contactimporter_social'), $aInsert);
    }    
}
?>